package com.edwin.websitebe.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edwin.websitebe.dto.LoginDTO;
import com.edwin.websitebe.model.Game;
import com.edwin.websitebe.model.Member;
import com.edwin.websitebe.model.MemberGame;
import com.edwin.websitebe.model.User;
import com.edwin.websitebe.service.MemberGameService;
import com.edwin.websitebe.service.MemberService;
import com.edwin.websitebe.util.OSSUtil;
import com.edwin.websitebe.util.TokenUtil;
import com.edwin.websitebe.vo.LoginVO;
import com.edwin.websitebe.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

@RestController
@RequestMapping("/member")
@Slf4j
@CrossOrigin
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberGameService memberGameService;

    private final String DEFAULT_PASSWORD = "123456";

    @PostMapping("/memberLogin")
    public ResultVO memberLogin(@Validated @RequestBody LoginDTO dto) {

        Member member = memberService.getByMemberName(dto.getUsername());
        if (Objects.isNull(member)) {
            return new ResultVO().fail("1", "用户不存在");
        }

        boolean match = dto.getPassword().equals(member.getPassword());
        if (match) {
            LoginVO loginVO = new LoginVO();
            loginVO.setToken(TokenUtil.createToken(member.getId()));
            return new ResultVO().success(loginVO);
        } else {
            return new ResultVO().fail("1", "密码错误");
        }

    }

    @PostMapping("/memberRegister")
    public ResultVO memberRegister(@Validated @RequestBody LoginDTO dto) {

        Member member = memberService.getByMemberName(dto.getUsername());
        if (Objects.nonNull(member)) {
            return new ResultVO().fail("1", "用户名已存在");
        }

        member = new Member();
        member.setMemberName(dto.getUsername());
        member.setPassword(dto.getPassword());
        member.setCreateTime(LocalDateTime.now());
        member.setNickname(dto.getUsername());
        boolean saved = memberService.save(member);
        if (saved) {
            return new ResultVO().success();
        } else {
            return new ResultVO().fail("1", "注册失败，请重试");
        }


    }

    @GetMapping("/page")
    public ResultVO page(@RequestParam Long page, @RequestParam Long pageSize, @RequestParam(required = false) String nickname) {
        LambdaQueryWrapper<Member> wrapper = new QueryWrapper<Member>().lambda()
                .like(Objects.nonNull(nickname), Member::getNickname, nickname)
                .orderByDesc(Member::getCreateTime);
        Page<Member> pageResult = memberService.page(Page.of(page, pageSize), wrapper);
        return new ResultVO().success(pageResult);
    }

    @GetMapping("/getById")
    public ResultVO getById(@RequestParam Long id) {
        Member member = memberService.getById(id);
        return new ResultVO().success(member);
    }

    @GetMapping("/getLoginMember")
    public ResultVO getLoginMember(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        Long memberId = TokenUtil.getUserId(token);
        Member member = memberService.getById(memberId);
        return new ResultVO().success(member);
    }

    @PostMapping("/saveOrUpdate")
    public ResultVO saveOrUpdate(@RequestBody Member member) {
        if (member.getId() == null) {
            member.setPassword(DEFAULT_PASSWORD);
            Member byMemberName = memberService.getByMemberName(member.getMemberName());
            if (Objects.nonNull(byMemberName)) {
                return new ResultVO().fail("1", "会员名称重复");
            }
        }
        memberService.saveOrUpdate(member);
        return new ResultVO().success();
    }

    @DeleteMapping("/deleteMember")
    public ResultVO deleteMember(@RequestParam Long memberId) {
        Member member = memberService.getById(memberId);
        if (member == null) {
            return new ResultVO().success();
        }

        if (StringUtils.isNotBlank(member.getAvatarUrl())) {
            // 删除旧头像
            String avatarUrl = member.getAvatarUrl();
            String oldAvatarPath = OSSUtil.parseFilePath(avatarUrl);
            if (FileUtil.exist(oldAvatarPath)) {
                FileUtil.del(oldAvatarPath);
            }
        }

        // 删除绑定游戏
        LambdaQueryWrapper<MemberGame> wrapper = new QueryWrapper<MemberGame>().lambda()
                .eq(MemberGame::getMemberId, memberId);
        memberGameService.remove(wrapper);

        memberService.removeById(memberId);
        return new ResultVO().success();
    }

    @PostMapping("/uploadMemberAvatar")
    public ResultVO uploadMemberAvatar(MultipartFile file, Long memberId, HttpServletRequest request) throws IOException {
        Member member = memberService.getById(memberId);
        if (member == null) {
            return new ResultVO().success();
        }

        if (StringUtils.isNotBlank(member.getAvatarUrl())) {
            // 删除旧头像
            String avatarUrl = member.getAvatarUrl();
            String oldAvatarPath = OSSUtil.parseFilePath(avatarUrl);
            if (FileUtil.exist(oldAvatarPath)) {
                FileUtil.del(oldAvatarPath);
            }
        }

        log.info("开始上传会员头像");
        String filename = file.getOriginalFilename();
        String extend = filename.substring(filename.lastIndexOf("."));

        String objName = "img/member/" + memberId + "-" + IdUtil.simpleUUID() + "-memberAvatarUrl" + extend;
        String url = OSSUtil.uploadFile(objName, file);
        String filePath = OSSUtil.BASE_PATH + objName;
        if (StringUtils.isNotEmpty(url)) {
            log.info("开始缩放图片");
            ImgUtil.scale(
                    FileUtil.file(filePath),
                    FileUtil.file(filePath),
                    0.5F
            );
            log.info("缩放完成");
        }
        log.info("会员头像上传完成: url: {}", url);
        log.info("开始更新会员数据");
        member.setAvatarUrl(url);
        memberService.updateById(member);
        return new ResultVO().success();
    }

}
